package hy;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.RetryUntilElapsed;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DisLock {
    String url="192.168.188.100:2181";
    CuratorFramework cli;
    @Before
    public  void init(){
        //重试策略，超时后重连，每三秒就重新连接，连接一共用时如果超过10秒就不再重连
        RetryPolicy r=new RetryUntilElapsed(10000,3000);
        cli= CuratorFrameworkFactory.builder().connectString(url).sessionTimeoutMs(1000).retryPolicy(r).build();
        cli.start();
    }

    @After
    public void close(){
        cli.close();
    }

    @Test//排它锁
    public void mutex()throws Exception{
        InterProcessLock lock=new InterProcessMutex(cli,"/locks");
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        lock.release();
        System.out.println("成功释放锁");
    }

    @Test//可读读，不可读写，不可写读
    public void readLock()throws Exception{
        InterProcessReadWriteLock rl=new InterProcessReadWriteLock(cli,"/locks");
        System.out.println("等待获取锁对象....");
        InterProcessLock lock= rl.readLock();
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        lock.release();
        System.out.println("成功释放锁");
    }
    @Test//不可读写，不可写读
    public void writeLock()throws Exception{
        InterProcessReadWriteLock rl=new InterProcessReadWriteLock(cli,"/locks");
        System.out.println("等待获取锁对象....");
        InterProcessLock lock= rl.writeLock();
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        lock.release();
        System.out.println("成功释放锁");
    }
}